<?php

namespace app\suguan\middleware;

use app\suguan\utils\ErrorCode;
use app\suguan\utils\Result;
use app\suguan\utils\User;

class Auth
{
    // 白名单
    private $_white_url = [
        'index/index', // 首页
        'user/login', // 登录
        'ueditor/index',
        'ueditor/index',
        'upload/uploadImage',

    ];
    // 登录后的白名单
    private $_login_white_url = [
        'user/info', // 登录
        'upload/uploadImage',
    ];


    //无需验证的控制器
    private $_white_controller = [
        'upload'
    ];

    public function handle($request, \Closure $next)
    {


        // 当前控制器
        $controller = request()->controller();
        $action = request()->action();
        $rule = strtolower($controller. '/'. $action);
        // 白名单，通过
        if (in_array(strtolower($controller), $this->_white_controller)) {
            return $next($request);
        }
        if (in_array($rule, $this->_white_url)) {
            return $next($request);
        }
        $token = User::getToken();
        if (empty($token)) {
            return Result::error(ErrorCode::LOGIN_FAIL);
        }
        // 超级管理员
        $uid = User::getUid();
        if (empty($uid)) {
            return Result::error(ErrorCode::LOGIN_FAIL);
        }
        // 白名单，通过
        if (in_array($rule, $this->_login_white_url)) {
            return $next($request);
        }
        $userinfo = model('Admin')->getUserInfo($uid);
        if ($userinfo['is_super']) {
            return $next($request);
        }
        // 权限判断
        $auth = model('AdminRole')->getAuth($userinfo['role_id']);
        if (!in_array($rule, $auth)) {
            return Result::error(ErrorCode::NO_AUTH);
        }

        return $next($request);
    }
}